﻿using Common.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using static System.Net.Mime.MediaTypeNames;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CommonController : ControllerBase
    {
        [HttpPost("upload")]
        public async Task<ApiResult> UploadAsync(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return ResultHelper.Error("文件为空");

            string fileName = file.FileName;
            string uniqueFileName = GetUniqueFileName(fileName);
            string filePath = Path.Combine("D:", "img", uniqueFileName);
            

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            //返回文件名
            return ResultHelper.Success(uniqueFileName);
        }

        //解决文件重名
        private string GetUniqueFileName(string fileName)
        {
            fileName =Guid.NewGuid().ToString()
                       + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff")
                       + Path.GetExtension(fileName);
            return fileName;
        }

        [HttpGet("download/{fileName}")]
        public async Task<IActionResult> DownloadFile(string fileName)
        {
            // 文件路径
            string filePath = @"D:\img\"+fileName;

            // 如果文件不存在，返回 404 Not Found
            if (!System.IO.File.Exists(filePath))
            {
                return NotFound();
            }

            // 读取图片为字节数组
            byte[] imageBytes;
            try
            {
                imageBytes = System.IO.File.ReadAllBytes(filePath);
            }catch (Exception ex)
            {
                await Console.Out.WriteLineAsync(ex.Message);
                return NotFound();
            }
            // 返回图片内容，并指定 Content-Type 为 image/jpeg
            return File(imageBytes, "image/jpeg");
        }

    }
}
